package com.xxx.meter.ui.patrol.machine.home;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.zxing.client.android.Intents;
import com.xxx.meter.R;
import com.xxx.meter.base.BaseActivity;
import com.xxx.meter.model.data.meter.MeterEntry;
import com.xxx.meter.model.data.meter.MeterUtil;
import com.xxx.meter.model.data.patrol.PatrolEntry;
import com.xxx.meter.model.data.patrol.PatrolUtil;
import com.xxx.meter.model.http.Api;
import com.xxx.meter.model.http.ApiCallback;
import com.xxx.meter.model.http.bean.MachineChildBean;
import com.xxx.meter.model.http.bean.MachineInfoBean;
import com.xxx.meter.model.http.bean.MachineTypeBean;
import com.xxx.meter.model.http.bean.PatrolBean;
import com.xxx.meter.model.http.bean.SubmitBean;
import com.xxx.meter.model.http.bean.base.BaseBean;
import com.xxx.meter.model.http.bean.base.BooleanBean;
import com.xxx.meter.model.http.bean.base.PageBean;
import com.xxx.meter.model.utils.ButtonUtil;
import com.xxx.meter.model.utils.PermissionUtil;
import com.xxx.meter.model.utils.ToastUtil;
import com.xxx.meter.ui.main.SweepActivity;
import com.xxx.meter.ui.main.view.ViewPagerAdapter;
import com.xxx.meter.ui.meter.reading.home.MeterReadingActivity;
import com.xxx.meter.ui.meter.reading.home.MeterReadingFragment;
import com.xxx.meter.ui.meter.reading.info.MeterReadingInfoActivity;
import com.xxx.meter.ui.patrol.machine.back.PatrolMachineBackWindow;
import com.xxx.meter.ui.patrol.machine.info.PatrolMachineInfoActivity;
import com.xxx.meter.ui.submit.SubmitWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class PatrolMachineActivity extends BaseActivity {

    @BindView(R.id.main_title)
    TextView mTitle;
    @BindView(R.id.main_tabLayout)
    TabLayout mTabLayout;
    @BindView(R.id.main_viewPager)
    ViewPager mViewPager;
    @BindView(R.id.not_data)
    ImageView mNotData;
    @BindView(R.id.not_net)
    ImageView mNotNet;
    @BindView(R.id.main_data)
    LinearLayout mMainData;

    private List<Fragment> mFragmentList = new ArrayList<>();
    private List<String> mTitleList = new ArrayList<>();
    private ViewPagerAdapter mAdapter;
    private List<MachineTypeBean> mTypeList = new ArrayList<>();
    private SubmitWindow mSubmitDialog;
    private PatrolMachineBackWindow mBackWindow;
    private MachineChildBean sweepBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_patrol;
    }

    @Override
    protected void initData() {
        mTitle.setText("设备巡机");

        mAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList, mTitleList);
        mViewPager.setAdapter(mAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.setOffscreenPageLimit(3);

        loadDeviceTypeList();
    }

    @OnClick({R.id.main_return, R.id.patrol_sweep, R.id.patrol_submit, R.id.not_data, R.id.not_net})
    public void OnClick(View view) {
        if (ButtonUtil.isFastClick()) return;
        switch (view.getId()) {
            case R.id.patrol_sweep:
                if (PermissionUtil.checkPermission(this, PermissionUtil.READ_PERMISSION, PermissionUtil.WRITE_PERMISSION, PermissionUtil.CAMERA_PERMISSION)) {
                    startActivityForResult(new Intent(this, SweepActivity.class), 1);
                }
                break;
            case R.id.patrol_submit:
                if (PatrolUtil.isCheck()) {
                    //验证是否编写过备注文案
                    mBackWindow = PatrolMachineBackWindow.getInstance(this, new PatrolMachineBackWindow.Callback() {
                        @Override
                        public void callback(String data) {
                            PatrolUtil.saveSubmitData(data);
                            mSubmitDialog = SubmitWindow.getInstance(PatrolMachineActivity.this, 0, new SubmitWindow.Callback() {
                                @Override
                                public void onResponse(List<SubmitBean> list) {
                                    String submitData = PatrolUtil.getSubmitData(list);
                                    submitMachineData(submitData);
                                }
                            });
                            mSubmitDialog.show();
                        }
                    });
                    mBackWindow.show();
                } else {
                    ToastUtil.showToast("请先巡查机器");
                }
                break;
            case R.id.not_data:
                loadDeviceTypeList();
                break;
            case R.id.not_net:
                loadDeviceTypeList();
                break;
            case R.id.main_return:
                finish();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean result = PermissionUtil.onRequestPermissionsResult(permissions, grantResults);
        if (result) {
            startActivityForResult(new Intent(this, SweepActivity.class), 1);
        } else {
            if (PermissionUtil.checkPermission(this, PermissionUtil.READ_PERMISSION, PermissionUtil.WRITE_PERMISSION, PermissionUtil.CAMERA_PERMISSION)) {
                startActivityForResult(new Intent(this, SweepActivity.class), 1);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫码返回的
        if (resultCode == Activity.RESULT_OK && data != null) {
            String content = data.getStringExtra(Intents.Scan.RESULT);
            loadSweepDevice(content);
        }
    }

    /**
     * @Model 加载巡机类型列表
     */
    private void loadDeviceTypeList() {
        Api.getInstance().getDeviceTypeList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiCallback<PageBean<MachineTypeBean>>(this, true) {

                    @Override
                    public void onSuccess(PageBean<MachineTypeBean> listPageBean) {
                        mTypeList.clear();
                        mTypeList.addAll(listPageBean.getList());

                        int size = mTypeList.size();
                        for (int i = 0; i < size; i++) {
                            String type = mTypeList.get(i).getType();
                            if (type.equals("21")) {
                                mTypeList.remove(i);
                                i--;
                                break;
                            }
                        }

                        mTitleList.clear();
                        mFragmentList.clear();
                        for (MachineTypeBean machineBean : mTypeList) {
                            mTitleList.add(machineBean.getName());
                            mFragmentList.add(PatrolMachineFragment.getInstance(machineBean.getType()));
                        }
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(int errorCode, String errorMessage) {
                        ToastUtil.showToast(errorMessage);
                    }
                });
    }

    /**
     * @Model 加载扫描设备
     */
    private void loadSweepDevice(String sweepCode) {
        Api.getInstance().sweepDevice(sweepCode, "1")
                .flatMap(new Function<BaseBean<MachineChildBean>, ObservableSource<BaseBean<List<PatrolBean>>>>() {
                    @Override
                    public ObservableSource<BaseBean<List<PatrolBean>>> apply(BaseBean<MachineChildBean> objectBaseBean) {
                        if (objectBaseBean == null) throw new RuntimeException("服务器异常");
                        sweepBean = objectBaseBean.getData();
                        if (sweepBean == null) throw new RuntimeException("服务器异常");

                        PatrolEntry.DataItemEntry machineChild = PatrolUtil.createMachineChild(sweepBean);
                        //说明本地已经有参数
                        if (machineChild != null) {
                            sweepBean = machineChild.getMachineChildBean();
                            throw new RuntimeException("1225");
                        }

                        return Api.getInstance().getPatrolDeviceInfoList(sweepBean.getType(), sweepBean.getId());
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiCallback<List<PatrolBean>>(this, false) {

                    @Override
                    public void onSuccess(List<PatrolBean> list) {
                        if (sweepBean != null) {
                            PatrolUtil.updateMachineInfo(sweepBean.getType(), sweepBean.getId(), list);
                            Intent intent = new Intent(PatrolMachineActivity.this, PatrolMachineInfoActivity.class);
                            intent.putExtra("machineId", sweepBean.getId());
                            intent.putExtra("machineType", sweepBean.getType());
                            intent.putExtra("machineName", sweepBean.getName());
                            startActivity(intent);

                            for (int i = 0; i < mTypeList.size(); i++) {
                                if (mTypeList.get(i).getType().equals(sweepBean.getType())) {
                                    mViewPager.setCurrentItem(i);
                                    ((PatrolMachineFragment) mFragmentList.get(i)).onRefresh();
                                    break;
                                }
                            }
                        } else {
                            ToastUtil.showToast("服务器异常");
                        }
                    }

                    @Override
                    public void onError(int errorCode, String errorMessage) {
                        if ("1225".equals(errorMessage)) {
                            Intent intent = new Intent(PatrolMachineActivity.this, PatrolMachineInfoActivity.class);
                            intent.putExtra("machineId", sweepBean.getId());
                            intent.putExtra("machineType", sweepBean.getType());
                            intent.putExtra("machineName", sweepBean.getName());
                            startActivity(intent);
                            return;
                        }
                        ToastUtil.showToast(errorMessage);
                    }
                });
    }

    /**
     * @Model 提交巡机数据
     */
    private void submitMachineData(String submitData) {
        Api.getInstance().submitPatrolInfo(submitData)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiCallback<BooleanBean>(this, true) {

                    @Override
                    public void onSuccess(BooleanBean bean) {
                        if (bean.isResult()) {
                            PatrolUtil.cleanMachine();
                            //全部刷新数据
                            for (Fragment fragment : mFragmentList) {
                                ((PatrolMachineFragment) fragment).onRefresh();
                            }
                            if (mSubmitDialog != null) {
                                mSubmitDialog.dismiss();
                                mSubmitDialog = null;
                            }
                            ToastUtil.showToast("提交成功");
                        } else {
                            ToastUtil.showToast("服务器异常");
                        }
                    }

                    @Override
                    public void onError(int errorCode, String errorMessage) {
                        ToastUtil.showToast(errorMessage);
                        if (mSubmitDialog != null) {
                            mSubmitDialog.dismiss();
                            mSubmitDialog = null;
                        }
                    }
                });
    }

}
